// 控制台打印
// 参数拼接

import * as Blockly from 'blockly/core'

const mixinObj = {
  mutationToDom: function () {
    var container = Blockly.utils.xml.createElement('mutation')
    container.setAttribute('items', this.itemCount_)
    return container
  },
  domToMutation: function (xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10) || 0
    this.updateShape_()
  },

  updateShape_: function () {
    // Add new inputs.
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i)
      }
    }
    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i)
      i++
    }
  }
}

const helpFun = function () {
  // 初始化的参数个数
  this.itemCount_ = 1
  this.updateShape_()
}
Blockly.Extensions.registerMutator('console_mutator', mixinObj, helpFun)

const consoleJson = {
  'type': 'console_print',
  'message0': '控制台打印%1 %2',
  'args0': [
    {
      'type': 'field_label_serializable',
      'name': 'Type',
      'text': '提示信息'
    },
    {
      'type': 'input_dummy',
      'name': 'PARAM_INPUT'
    }

  ],
  'style': 'tool_blocks',
  'previousStatement': null,
  'nextStatement': null,
  'inputsInline': true,
  'tooltip': '',
  'helpUrl': '',
  'mutator': 'console_mutator'
}
Blockly.Blocks['console_print'] = {
  init: function () {
    this.jsonInit(consoleJson)
  }
}

Blockly.JavaScript['console_print'] = function (block) {
  const type = block.getFieldValue('Type')
  const elements = new Array(block.itemCount_)
  const options = [
    { key: 'log', label: '提示信息' },
    { key: 'warn', label: '警告信息' },
    { key: 'error', label: '错误信息' },
    { key: 'dir', label: '检查对象' },
    { key: 'time', label: '计时开始' },
    { key: 'timeEnd', label: '计时结束' }
  ]
  const res = options.find(item => item.label === type)
  const method = res?.key || 'log'

  for (var i = 0; i < block.itemCount_; i++) {
    elements[i] = Blockly.JavaScript.valueToCode(block, 'ADD' + i,
      Blockly.JavaScript.ORDER_COMMA) || ''
  }
  const params = elements.join(',')
  return `console.${method}(${params})\n`
}

// 2------------------------参数拼接----------

Blockly.Blocks['json_generate'] = {
  init: function () {
    this.appendDummyInput().appendField(
      new Blockly.FieldLabelSerializable('JSON参数拼接'), 'NAME_LABEL')
    this.appendDummyInput().setVisible(false)
    this.appendDummyInput().appendField(
      new Blockly.FieldTextInput(), 'CODE').setVisible(false)
    this.setInputsInline(true)
    this.setOutput(true, null)
    this.setStyle('tool_blocks')
    this.setTooltip('')
    this.setHelpUrl('')
  }
}

Blockly.JavaScript['json_generate'] = function (block) {
  let code = block.getFieldValue('CODE')
  const str = decodeURIComponent(code).trim()
  if (str.startsWith('async')) {
    code = `await (${str})()`
  } else if (str) {
    code = `(${str})()`
  } else {
    code = `{}`
  }
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]
}
